#include "Geometry.h"
#include "Renderer.h"

namespace graphics
{

Geometry::Geometry()
{
	m_VertexType = 0;
	P_Texture = NULL;
	m_VertexBuffer = 0;
}
Geometry::~Geometry()
{
	V_Vector_P.clear();
	V_Vector_PC.clear();
	V_Vector_PT.clear();
	SAFE_RELEASE( P_Texture );
	SAFE_RELEASE( m_VertexBuffer );
}
void Geometry::Initialize(D3DDevice ptr)
{
	m_Device = ptr;
}
void Geometry::addVertex(float3 position)
{
	m_VertexType = V_Type_P;
	V_Vector_P.push_back(V_P(position));
	V_Vertices.push_back(position);
}
void Geometry::addVertex(float3 position,float3 color)
{
	m_VertexType = V_Type_PC;
	V_Vector_PC.push_back(V_PC(position,color));
	V_Vertices.push_back(position);
}
void Geometry::addVertex(float3 position,float2 texture)
{
	m_VertexType = V_Type_PT;
	V_Vector_PT.push_back(V_PT(position,texture));
	V_Vertices.push_back(position);
}
void Geometry::applyTexture(char* filename)
{
	text* tFileName;
	int len = strlen(filename) + 1;
	tFileName = new text [len];
	mbstowcs(tFileName, filename, len);

	D3DXCreateTextureFromFile(m_Device, tFileName, &P_Texture);

	delete [] tFileName;
}
void Geometry::setup()
{
	int i = 0;

	if(m_VertexType == V_Type_P)
	{
		m_Device->CreateVertexBuffer(V_Vector_P.size() * sizeof(V_P), D3DUSAGE_WRITEONLY,
			0, D3DPOOL_MANAGED,	&m_VertexBuffer, 0);
		V_P* v = 0;
		m_VertexBuffer->Lock(0,0, (void**)&v, 0);

		for(vector<V_P>::iterator Iter = V_Vector_P.begin(); Iter != V_Vector_P.end(); Iter++,i++)
			v[i] = *Iter;
		m_VertexBuffer->Unlock();
	}

	if(m_VertexType == V_Type_PC)
	{
		m_Device->CreateVertexBuffer(V_Vector_PC.size() * sizeof(V_PC), D3DUSAGE_WRITEONLY,
			0, D3DPOOL_MANAGED,	&m_VertexBuffer, 0);
		V_PC* v = 0;
		m_VertexBuffer->Lock(0,0, (void**)&v, 0);

		for(vector<V_PC>::iterator Iter = V_Vector_PC.begin(); Iter != V_Vector_PC.end(); Iter++,i++)
			v[i] = *Iter;
		m_VertexBuffer->Unlock();
	}

	if(m_VertexType == V_Type_PT)
	{
		m_Device->CreateVertexBuffer(V_Vector_PT.size() * sizeof(V_PT), D3DUSAGE_WRITEONLY,
			0, D3DPOOL_MANAGED,	&m_VertexBuffer, 0);
		V_PT* v = 0;
		m_VertexBuffer->Lock(0,0, (void**)&v, 0);

		for(vector<V_PT>::iterator Iter = V_Vector_PT.begin(); Iter != V_Vector_PT.end(); Iter++,i++)
			v[i] = *Iter;
		m_VertexBuffer->Unlock();
	}
}

IDirect3DVertexBuffer9* Geometry::getVertexBuffer()
{
	return m_VertexBuffer;
}
int Geometry::getVertexType()
{
	return m_VertexType;
}
void Geometry::Draw(Renderer& RendererAddress)
{
	RendererAddress.Draw(this);
}

vector<float3> Geometry::getVertices()
{
	return V_Vertices;
}

poly::Polygon Geometry::getPolygon()
{
	vector<float3> thisVertices = getVertices();
	poly::Polygon thisPolygon;

	vector<float3>::iterator iter1;
	for(iter1 = thisVertices.begin();iter1 != thisVertices.end();iter1++)
	{
		thisPolygon.push_back(*iter1);
	}

	return thisPolygon;
}

}/* namespace graphics */
